/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.action.system;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.dozer.MappingException;
import org.grayrabbit.cms.action.common.BaseAction;
import org.grayrabbit.cms.constant.ConfigCode;
import org.grayrabbit.cms.constant.ConstantEnum.Module;
import org.grayrabbit.cms.constant.ConstantEnum.OperAct;
import org.grayrabbit.cms.constant.ConstantWebApp;
import org.grayrabbit.cms.constant.DBInitId;
import org.grayrabbit.cms.constant.DictionaryStaticValues;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.Config;
import org.grayrabbit.cms.entity.Dictionary;
import org.grayrabbit.cms.entity.Role;
import org.grayrabbit.cms.service.system.AdminService;
import org.grayrabbit.cms.service.system.ConfigService;
import org.grayrabbit.cms.service.system.RoleService;
import org.grayrabbit.cms.util.MD5;
import org.grayrabbit.cms.vo.system.AdminBean;
import org.grayrabbit.dao.util.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

/**
 * <b>AdminAction</b> Struts2 action�?





 * @version 1.0,创建时间:2011-05-16 15:55:12 
 */
@Controller
@Scope("prototype")
@Results( {
		@Result(name = "reload", type = "redirect", location = "admin-list.action"),
		@Result(name = "input", type = "dispatcher", location = "admin-input.jsp"),
		@Result(name = "success", type = "dispatcher", location = "admin-list.jsp")
		}
		)
@ParentPackage("manage-default")
public class AdminAction extends BaseAction<AdminBean> {
	private static final long serialVersionUID = -1L;
	public static final String EDITSELF = "editself";
	private static final Logger log = LoggerFactory.getLogger(AdminAction.class);
	
	//Service接口接入
	@Autowired
	@Qualifier("configServiceImpl")
	private ConfigService configService;
	
	//Service接口接入
	@Autowired
	@Qualifier("roleServiceImpl")
	private RoleService roleService;
	
	//Service接口接入
	@Autowired
	@Qualifier("adminServiceImpl")
	private AdminService adminService;
	
	private String operTargetId;
	private String operCode;
	private String operTargetType;
	private String orig;
	private List<Dictionary> isActiveList;
	private List<Dictionary> dicArea;
	private String info;
	private String infoReturn;
	//批量操作时使用的传入的ID
	private String ids;
	//管理员列表
	private List<Admin> adminSelectList;
	//角色列表
	private List<Role> roleLists;
	//VO对象，由前端页面数据组装
	private AdminBean admin;
	//分页对象
	@SuppressWarnings("rawtypes")
	private Page page = new Page(MAX_PAGE_NUM,true);

	private String adminIds;
	
	private String countryArea;
	private String provinceArea;
	private String cityArea;
	private String unitCode;
	private String fullName;
	private String selfInfo;
	private String paw;
	
	public String getPaw() {
		return paw;
	}

	public void setPaw(String paw) {
		this.paw = paw;
	}

	public String getSelfInfo() {
		return selfInfo;
	}

	public void setSelfInfo(String selfInfo) {
		this.selfInfo = selfInfo;
	}

	public String getFullName() {
		return fullName;
	}

	public void setFullName(String fullName) {
		this.fullName = fullName;
	}

	/**
	 * 在执行（struts2的action调用时）list()方法前执行本方法
	 */
	public void prepareList(){
		prepareModel();
	}
	
	/**
	 * 在执行任何其它action方法（struts2的action调用时）前执行本方法
	 */
	public void prepare(){
		if(admin==null){
			admin = new AdminBean();
		}
	}
	/**
	 * 实现ModelDriven的接口简例前端页的bean组装写法,
	 *  如：
	 *	<pre>
	 *		<code> name="user.userName"</code>
	 *	改写成：
	 *		<code> name="userName"</code>
	 *	action实例中，会自动组成user成员变量
	 *	</pre>
	 */
	public AdminBean getModel() {
		return admin;
	}
	
	@Override
	protected void prepareModel(){
		if(null!=admin&&StringUtils.isNotBlank(admin.getAdminId())){
			admin = (AdminBean)dozer.map(adminService.getAdmin(admin.getAdminId()),AdminBean.class);
		}
	}

	/**
	 * 删除<b>Admin</b>记录的方法，成员变量<b>key</b>为主键的String数组，以主键方式进行删作
	 * 删除成功后，返回"reload"，然后跳转到admin-list.action
	 */
	@Override
	@Action(value="admin-delete")
	public String delete(){
		if((admin!=null)&&(StringUtils.isNotBlank(admin.getAdminId()))){
			if(!DBInitId.CMS_SUPPER_ADMIN_ID.trim().equals(admin.getAdminId())){
				String[] str=new String[1];
				str[0]=admin.getAdminId();
				adminService.delete(str);
			}
			
		}else{
			if(key!=null){
				adminService.delete(key);
			}else{
				String[] idBatchs=getBatchIds();
				adminService.delete(idBatchs);
			}
			
		}
		return RELOAD;
	}
	
	/**
	 * Admin的列表方法，通过成员变量<b>page�?{insClassName}</b>调用service接口，更新page
	 * 执行成功后，将映射到admin-list.jsp页面
	 */
	@SuppressWarnings("unchecked")
	@Override
	@Action(value="admin-list")
	public String list(){
		if(admin!=null&&("--").equals(admin.getActive())){
			admin.setActiveStatus(null);
		}else if(admin!=null&&("true").equals(admin.getActive())){
			admin.setActiveStatus(true);
		}else if(admin!=null&&("false").equals(admin.getActive())){
			admin.setActiveStatus(false);
		}
		adminService.list(page,admin);
		roleLists = roleService.showAllRoles(true);
		isActiveList = this.dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_ACTIVE);
		isActiveList = isActiveList==null?DictionaryStaticValues.EMPTY_DICTIONARY_LIST:isActiveList;
		return SUCCESS;
	}
	
	/**
	 * Admin的新增与编辑的方法执行成功能
	 * 将映射到admin-input.jsp
	 */
	@Action(value="admin-input")
	public String input(){
		//FIXME input页面需要修改 2012-04-17
		/*if(dictionaryService.getParentDictionaryList(DictionaryStaticValues.AREA)!=null){
			dicArea = dictionaryService.getDictionaryListDictionaryKey(DictionaryStaticValues.CHINA, DictionaryStaticValues.AREA);
		}
		
		Admin currentAdmin=(Admin)getSessionValue(ConstantWebApp.CURRENT_ADMIN);
		if(null==orig||("").equals(orig.trim())){
			orig="input";
		}else if(("editSelf").equals(orig.trim())){
			admin.setAdminId(currentAdmin.getAdminId());
			if("selfInfo".equals(selfInfo)){
				selfInfo = "selfInfo";
			}
		}
		prepareModel();
		roleLists = roleService.showAllRoles(true);
		page.setPageSize(5);
		showAssociatorsService.list(page, null);*/
		
		return INPUT;
	}
	
	private String[] getBatchIds(){
		String[] idBatchs=null;
		if(StringUtils.isNotBlank(ids)){
			idBatchs=ids.split("@");
		}
		return idBatchs;
	}
	
	/**
	 * save or update Admin的方法，将成员property admin转成Admin实例，执行保存；
	 * 执行成功后，返回"reload"，然后跳转到admin-list.action
	 */
	@Override
	@Action(value="admin-save",
			results={@Result(name="reload",type="redirectAction",params={"actionName","admin-list?info=${infoReturn}"}),
					 @Result(name="editself",type="redirectAction",params={"actionName","admin-input?orig=editSelf&selfInfo=selfInfo"})}
		)
	public String save(){
		try {
			Admin obj = (Admin) dozer.map(admin, Admin.class);
			Admin currentAdmin=(Admin)getSessionValue(ConstantWebApp.CURRENT_ADMIN);
			//新建信息
			if(!StringUtils.isNotBlank(obj.getAdminId())){
				obj.setAdminId(null);
				Config config=configService.getConfigByAttrKey(ConfigCode.INIT_ADMIN_PASSWORD);
				obj.setPasswd(MD5.getMD5Str(config.getConfigAttrValue()));
				obj.setActiveStatus(true);
				obj.setCreateTime(new java.util.Date());
				
				if(null!=currentAdmin){
					obj.setCreateLoginName(currentAdmin.getLoginName());
					obj.setCreateRealName(currentAdmin.getRealName());
				}
			}
			
			if(null!=currentAdmin){
				obj.setUpdateLoginName(currentAdmin.getLoginName());
				obj.setUpdateRealName(currentAdmin.getRealName());
			}
			if("editSelf".equals(orig)){
				adminService.updateAdminSelf(obj);
				currentAdmin.setRealName(obj.getRealName());
				currentAdmin.setNickName(obj.getNickName());
				currentAdmin.setEmail(obj.getEmail());
				currentAdmin.setTelephone(obj.getTelephone());
				currentAdmin.setMobile(obj.getMobile());
				return EDITSELF;
			}
			obj.setUpdateTime(new java.util.Date());
			adminService.save(obj);
		} catch (MappingException e) {
			log.debug(e.getMessage());
		}
 
		if("editSelf".equals(orig)){
			return EDITSELF;
		}else{
			return RELOAD;
		}
	}

	@Action(value="admin-pwdupdate")
	public String passwordUpadate(){
		String text=null;
		Admin currentAdmin=(Admin)getSessionValue(ConstantWebApp.CURRENT_ADMIN);
		Admin obj=adminService.getAdmin(admin.getAdminId());
		if((StringUtils.isNotBlank(admin.getPasswd()))&&(StringUtils.isNotBlank(admin.getNewPasswdAgain()))
				&&(StringUtils.isNotBlank(admin.getNewPasswd()))){//三个都存在
			if(admin.getNewPasswd().equals(admin.getNewPasswdAgain())){//两个密码相同
				if(currentAdmin.getPasswd().equals(MD5.getMD5Str(admin.getPasswd()))){//密码正确
					obj.setPasswd(MD5.getMD5Str(admin.getNewPasswd()));//修改完成
					text="password.update.success";
					adminService.save(obj);
					setSessionValue(ConstantWebApp.CURRENT_ADMIN, obj);
				}else{
					text="password.not.correct";
				}
			}else{
				text="new.password.not.same";
			}
		}else{
			text="";
		}
		text=StringUtils.isNotBlank(text)?this.getText(text):"";
		return renderText(text);
	}
	
	/**
	 * 管理员选择列表
	 */
	@Action(value="admin-adminselectlist",
			results={@Result(name="success",location="/WEB-INF/content/system/admin-selectlist.jsp")
			}) 
	public String adminSelectList(){
	 adminSelectList=adminService.getAdminsByOper(operTargetId,operTargetType,operCode);
		return SUCCESS;
	}
	
	/**
	 * 更新实体
	 * @return
	 */
	@Action(value="admin-update")
	public String update(){
		return SUCCESS;
	}
	
	/**
	 * 禁用/启用账户
	 * @return
	 */
	@Action(value="admin-disableorenable",
			results={@Result(name="reload",type="redirectAction",params={"actionName","admin-list"})}
	)
	public String disableOrEnable(){
		if((admin!=null)&&(StringUtils.isNotBlank(admin.getAdminId()))){
			adminService.disableOrEnable(admin.getAdminId());
		}
		return RELOAD;
	}
	
	@Action(value="admin-activestatus",
			results={@Result(name="reload",type="redirectAction",params={"actionName","admin-list"})}
			)
	public String adminActiveStatus(){
		if((admin!=null)&&(admin.getActiveStatus()!=null)){
			String[] idBatchs=getBatchIds();
			adminService.adminActiveStatus(idBatchs,admin.getActiveStatus());
		}
		return RELOAD;
	}

	/**
	 * 重置密码
	 * @return
	 */
	@Action(value="admin-initPwd")
	public String initPwd(){
		String text="";
		Config config=configService.getConfigByAttrKey(ConfigCode.INIT_ADMIN_PASSWORD);
		try {
			if(null!=admin&&StringUtils.isNotBlank(admin.getAdminId())){
				adminService.initPwd(admin.getAdminId(), MD5.getMD5Str(config.getConfigAttrValue()));
				text="ok";
			}else{
				String[] idBatchs=getBatchIds();
				adminService.initPwd(idBatchs, MD5.getMD5Str(config.getConfigAttrValue()));
				text="ok";
			}			
		} catch (Exception e) {
			 text="no";
			 log.debug("密码初始化失败");
		}
		return renderText(text);
	}
	
	//名称唯一性验证
	@Action(value="admin-checknameunique")
	public String checkNameUnique(){
		Boolean unique=adminService.checkNameUnique(admin,admin.getAdminId());
		String text=null;
		if(!unique){
			//唯一，可用
			text="unique";
		}else{
			//已存在，不可用
			text="exist";
		}
		return renderText(text);
	}
	
	@Action(value="admin-getselectedadmins")
	public String getSelectedAdmins(){
		String[] adminId=adminIds.split("@");
		if(adminId!=null&&adminId.length>0){
			for(String str:adminId){
				log.debug(str);
			}
		}
		return renderText(adminIds);
	}
	
	
	public String getOperTargetId() {
		return operTargetId;
	}

	public void setOperTargetId(String operTargetId) {
		this.operTargetId = operTargetId;
	}

	public String getOperCode() {
		return operCode;
	}

	public void setOperCode(String operCode) {
		this.operCode = operCode;
	}

	public String getOperTargetType() {
		return operTargetType;
	}

	public void setOperTargetType(String operTargetType) {
		this.operTargetType = operTargetType;
	}
	/*
	 * return分页对象，默认实例化。如：page.pageNu=2,将更新相应的对象property
	 */
	@SuppressWarnings("rawtypes")
	public Page getPage() {
		return page;
	}
	//接收前端form,url提交参数组装成分页property
	@SuppressWarnings("rawtypes")
	public void setPage(Page page) {
		this.page = page;
	}
		
	public List<Admin> getAdminSelectList() {
		return adminSelectList;
	}

	public void setAdminSelectList(List<Admin> adminSelectList) {
		this.adminSelectList = adminSelectList;
	}
	
	/**return 前端页面数据组装VO对象,<b>AdminBean</b>*/
	public AdminBean getAdmin() {
		return admin;
	}

	public void setAdmin(AdminBean admin) {
		this.admin = admin;
	}
	
	public List<Role> getRoleLists() {
		return roleLists;
	}

	public void setRoleLists(List<Role> roleLists) {
		this.roleLists = roleLists;
	}
	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}
	public String getInfoReturn() {
		return infoReturn;
	}

	public void setInfoReturn(String infoReturn) {
		this.infoReturn = infoReturn;
	}

	public String getInfo() {
		return info;
	}

	public void setInfo(String info) {
		this.info = info;
	}
	

	public String getOrig() {
		return orig;
	}

	public void setOrig(String orig) {
		this.orig = orig;
	}

	public String getAdminIds() {
		return adminIds;
	}

	public void setAdminIds(String adminIds) {
		this.adminIds = adminIds;
	}

	public List<Dictionary> getIsActiveList() {
		return isActiveList;
	}

	public void setIsActiveList(List<Dictionary> isActiveList) {
		this.isActiveList = isActiveList;
	}

	public List<Dictionary> getDicArea() {
		return dicArea;
	}

	public void setDicArea(List<Dictionary> dicArea) {
		this.dicArea = dicArea;
	}

	public String getCountryArea() {
		return countryArea;
	}

	public void setCountryArea(String countryArea) {
		this.countryArea = countryArea;
	}

	public String getProvinceArea() {
		return provinceArea;
	}

	public void setProvinceArea(String provinceArea) {
		this.provinceArea = provinceArea;
	}

	public String getCityArea() {
		return cityArea;
	}

	public void setCityArea(String cityArea) {
		this.cityArea = cityArea;
	}
	public String getUnitCode() {
		return unitCode;
	}

	public void setUnitCode(String unitCode) {
		this.unitCode = unitCode;
	}
	
	@Action(value="myself",
			results={@Result(name="myself",type = "dispatcher",location="admin-infos.jsp")})
	public String editMyself(){
		String currentAdminId=(String)getSessionValue(ConstantWebApp.CURRENT_ADMIN_ID);
		Admin obj=adminService.getAdmin(currentAdminId);
		admin = (AdminBean)dozer.map(obj,AdminBean.class);
		return "myself";
	}
	
	@Action(value="updatemysef")
	public String updateMysef(){
		try {			
			String currentAdminId=(String)getSessionValue(ConstantWebApp.CURRENT_ADMIN_ID);
			Admin obj=adminService.getAdmin(currentAdminId);
			obj.setRealName(admin.getRealName());
			obj.setNickName(admin.getNickName());
			obj.setEmail(admin.getEmail());
			obj.setTelephone(admin.getTelephone());
			obj.setMobile(admin.getMobile());
			adminService.save(obj);
			addLog(Module.SYSTEM.getValue(), OperAct.EDIT.getValue(), currentAdminId, "修改了个人信息"); 
			return renderText("信息修改成功！");
		} catch (Exception e) {
			log.error("信息修改异常！", e);
			return renderText("信息修改异常！");
		} 
	}
	
	@Action(value="updatepdw")
	public String updatePdw(){
		try {			
			String currentAdminId=(String)getSessionValue(ConstantWebApp.CURRENT_ADMIN_ID);
			Admin obj=adminService.getAdmin(currentAdminId);
			if(StringUtils.isBlank(admin.getPasswd()) 
					|| !MD5.getMD5Str(admin.getPasswd()).equals(obj.getPasswd())){
				return renderText("原密码输入错误！");
			} 
			if(StringUtils.isBlank(admin.getNewPasswd())
					|| !admin.getNewPasswd().equals(admin.getNewPasswdAgain())){
				return renderText("新密码两次输入不一致！");
			}			
			obj.setPasswd(MD5.getMD5Str(admin.getNewPasswdAgain()));
			adminService.save(obj);
			addLog(Module.SYSTEM.getValue(), OperAct.EDIT.getValue(), currentAdminId, "修改了个人信息"); 
			return renderText("信息修改成功！");
		} catch (Exception e) {
			log.error("信息修改异常！", e);
			return renderText("信息修改异常！");
		} 
	}
	

}